package com.yejiali.backend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yejiali.backend.common.httpcode.HttpCodeEnum;
import com.yejiali.backend.entity.MedicalCase;
import com.yejiali.backend.entity.Patients;
import com.yejiali.backend.entity.dto.CaseAuditDTO;
import com.yejiali.backend.entity.dto.CasesPageInfoDTO;
import com.yejiali.backend.entity.vo.MedicalCaseInfoVo;
import com.yejiali.backend.response.Response;
import com.yejiali.backend.service.AuditService;
import com.yejiali.backend.service.PatientsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author:yejiali
 * @Date:2025/5/17-05-17-13:44
 * @Decsription:com.yejiali.backend.service.impl
 * @Version:1.0
 */
@Service
public class AuditServiceImpl implements AuditService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private PatientsService patientsService;

    /**
     * 状态为未审核病例，时间倒序，分页
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Response firstCheck(int pageNum, int pageSize) {
        Criteria criteria = Criteria.where("auditStatus").is("待初审");  // 使用精确匹配替代regex
        Query query = new Query(criteria)
                .with(Sort.by(Sort.Direction.DESC, "uploadTime"));

        long total = mongoTemplate.count(query, MedicalCase.class);
        if (total == 0) {
            return Response.success("暂无病例");
        }

        query.with(PageRequest.of(pageNum - 1, pageSize));
        List<MedicalCase> cases = mongoTemplate.find(query, MedicalCase.class);

        //封装
        List<MedicalCaseInfoVo> casesInfoListVo = new ArrayList<>();
        //设置病人名称
        for (MedicalCase medicalCase : cases) {
            //获取病人id
            Long patientId = medicalCase.getPatientId();
            // 获取患者（添加空校验）
            Patients patient = patientsService.getById(patientId);
            if (patient == null) {
                // 记录日志或跳过无效数据
                continue;
            }
            //复制
            MedicalCaseInfoVo medicalCaseInfoVo = BeanUtil.copyProperties(medicalCase, MedicalCaseInfoVo.class);
            medicalCaseInfoVo.setPatientName(patient.getName());
            medicalCaseInfoVo.setSex(patient.getSex());
            medicalCaseInfoVo.setBirthDate(patient.getBirthDate());
            casesInfoListVo.add(medicalCaseInfoVo);
        }
        CasesPageInfoDTO casesPageInfoDTO = new CasesPageInfoDTO(total,casesInfoListVo);
        return Response.success(casesPageInfoDTO,"查询成功");
    }


    /**
     * 状态为已初审，时间倒序，分页
     * @param pageNum
     * @param pageSize
     * @return
     */

    @Override
    public Response finalCheck(int pageNum, int pageSize) {
        Criteria criteria = Criteria.where("auditStatus").is("已初审");  // 使用精确匹配替代regex
        Query query = new Query(criteria)
                .with(Sort.by(Sort.Direction.DESC, "uploadTime"));

        long total = mongoTemplate.count(query, MedicalCase.class);
        if (total == 0) {
            return Response.success("暂无病例");
        }

        query.with(PageRequest.of(pageNum - 1, pageSize));
        List<MedicalCase> cases = mongoTemplate.find(query, MedicalCase.class);

        //封装
        List<MedicalCaseInfoVo> casesInfoListVo = new ArrayList<>();
        //设置病人名称
        for (MedicalCase medicalCase : cases) {
            //获取病人id
            Long patientId = medicalCase.getPatientId();
            // 获取患者（添加空校验）
            Patients patient = patientsService.getById(patientId);
            if (patient == null) {
                // 记录日志或跳过无效数据
                continue;
            }
            //复制
            MedicalCaseInfoVo medicalCaseInfoVo = BeanUtil.copyProperties(medicalCase, MedicalCaseInfoVo.class);
            medicalCaseInfoVo.setPatientName(patient.getName());
            medicalCaseInfoVo.setSex(patient.getSex());
            medicalCaseInfoVo.setBirthDate(patient.getBirthDate());
            casesInfoListVo.add(medicalCaseInfoVo);
        }
        CasesPageInfoDTO casesPageInfoDTO = new CasesPageInfoDTO(total,casesInfoListVo);
        return Response.success(casesPageInfoDTO,"查询成功");
    }

    /**
     * 修改审核状态
     *
     * @return
     */
    @Override
    public Response updateStatus(CaseAuditDTO caseAuditDTO) {
        // 根据ID查询病例
        Query query = new Query(Criteria.where("id").is(caseAuditDTO.getId()));
        MedicalCase medicalCase = mongoTemplate.findOne(query, MedicalCase.class);
        // 检查病例是否存在（这一步可以省略）
        if (medicalCase == null) {
            return Response.error(HttpCodeEnum.CASES_NOT_FOUND.getCode(),"病例不存在");
        }
        // 修改审核状态
        medicalCase.setAuditStatus(caseAuditDTO.getAuditStatus());
        // 保存修改后的病例
        mongoTemplate.save(medicalCase);
        return Response.success("修改成功");
    }

    /**
     * 根据审核状态查询病例
     * @param status
     * @param pageNum
     * @param pageSize
     * @return
     */
    public  Response queryCasesByStatus(String status, int pageNum, int pageSize){
        Criteria criteria = Criteria.where("auditStatus").is(status);  // 使用精确匹配替代regex
        Query query = new Query(criteria)
                .with(Sort.by(Sort.Direction.DESC, "uploadTime"));

        long total = mongoTemplate.count(query, MedicalCase.class);
        if (total == 0) {
            return Response.success("暂无病例");
        }

        query.with(PageRequest.of(pageNum - 1, pageSize));
        List<MedicalCase> cases = mongoTemplate.find(query, MedicalCase.class);

        //封装
        List<MedicalCaseInfoVo> casesInfoListVo = new ArrayList<>();
        //设置病人名称
        for (MedicalCase medicalCase : cases) {
            //获取病人id
            Long patientId = medicalCase.getPatientId();
            Patients patient = patientsService.getById(patientId);
            // 获取患者（添加空校验）
            if (patient == null) {
                // 记录日志或跳过无效数据
                continue;
            }
            //复制
            MedicalCaseInfoVo medicalCaseInfoVo = BeanUtil.copyProperties(medicalCase, MedicalCaseInfoVo.class);
            medicalCaseInfoVo.setPatientName(patient.getName());
            medicalCaseInfoVo.setSex(patient.getSex());
            medicalCaseInfoVo.setBirthDate(patient.getBirthDate());
            casesInfoListVo.add(medicalCaseInfoVo);
        }
        CasesPageInfoDTO casesPageInfoDTO = new CasesPageInfoDTO(total,casesInfoListVo);
        return Response.success(casesPageInfoDTO,"查询成功");
    }

    /**
     * 根据姓名查询病例
     * @param name
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Response searchByName(String name, int pageNum, int pageSize) {
        //构建查询条件
        LambdaQueryWrapper<Patients> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Patients::getName, name);
        List<Patients> patientsList = patientsService.list(queryWrapper);
        //判空
        if (patientsList.isEmpty()) {
            return Response.success("没有找到符合条件的病例");
        }
        //获取患者id集合
        List<Long> patientIds = patientsList.stream().map(Patients::getId).collect(Collectors.toList());
        //构建查询条件
        Query query = new Query(Criteria.where("patientId").in(patientIds));
        query.with(Sort.by(Sort.Direction.DESC, "uploadTime"));
        long total = mongoTemplate.count(query, MedicalCase.class);
        if (total == 0) {
            return Response.success("暂无病例");
        }
        query.with(PageRequest.of(pageNum - 1, pageSize));
        List<MedicalCase> cases = mongoTemplate.find(query, MedicalCase.class);
        //封装
        List<MedicalCaseInfoVo> casesInfoListVo = new ArrayList<>();
        //设置病人名称
        for (MedicalCase medicalCase : cases) {
            //获取病人id
            Long patientId = medicalCase.getPatientId();
            Patients patient = patientsService.getById(patientId);
            // 获取患者（添加空校验）
            if (patient == null) {
                // 记录日志或跳过无效数据
                continue;
            }
            //复制
            MedicalCaseInfoVo medicalCaseInfoVo = BeanUtil.copyProperties(medicalCase, MedicalCaseInfoVo.class);
            medicalCaseInfoVo.setPatientName(patient.getName());
            medicalCaseInfoVo.setSex(patient.getSex());
            medicalCaseInfoVo.setBirthDate(patient.getBirthDate());
            casesInfoListVo.add(medicalCaseInfoVo);
        }
        CasesPageInfoDTO casesPageInfoDTO = new CasesPageInfoDTO(total,casesInfoListVo);
        return Response.success(casesPageInfoDTO,"查询成功");
    }



}
